<template>
  <div class="finance-management">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>账户余额</span>
              <el-tag size="small" type="success">可提现</el-tag>
            </div>
          </template>
          <div class="card-value">¥{{ accountBalance.toFixed(2) }}</div>
          <div class="card-footer">
            <el-button type="primary" size="small" @click="handleWithdraw" :disabled="accountBalance <= 0">
              申请提现
            </el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>本月收入</span>
              <el-tag size="small" :type="monthlyIncome.trend > 0 ? 'success' : 'danger'">
                {{ monthlyIncome.trend > 0 ? '+' : '' }}{{ monthlyIncome.trend }}%
              </el-tag>
            </div>
          </template>
          <div class="card-value">¥{{ monthlyIncome.value.toFixed(2) }}</div>
          <div class="card-footer">
            上月：¥{{ monthlyIncome.lastMonth.toFixed(2) }}
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>本月支出</span>
              <el-tag size="small" :type="monthlyExpense.trend < 0 ? 'success' : 'danger'">
                {{ monthlyExpense.trend > 0 ? '+' : '' }}{{ monthlyExpense.trend }}%
              </el-tag>
            </div>
          </template>
          <div class="card-value">¥{{ monthlyExpense.value.toFixed(2) }}</div>
          <div class="card-footer">
            上月：¥{{ monthlyExpense.lastMonth.toFixed(2) }}
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>待结算金额</span>
            </div>
          </template>
          <div class="card-value">¥{{ pendingSettlement.toFixed(2) }}</div>
          <div class="card-footer">
            预计结算时间：{{ nextSettlementTime }}
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>收支趋势</span>
              <el-radio-group v-model="trendTimeRange" size="small">
                <el-radio-button label="week">近7天</el-radio-button>
                <el-radio-button label="month">近30天</el-radio-button>
                <el-radio-button label="year">近12个月</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" ref="trendChartRef"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>收支构成</span>
            </div>
          </template>
          <div class="chart-container" ref="compositionChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 收支明细 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>收支明细</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleExport">导出明细</el-button>
            <el-button type="success" @click="handleAddRecord">新增记录</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="收支类型">
          <el-select v-model="searchForm.type" placeholder="请选择" clearable>
            <el-option label="收入" value="income" />
            <el-option label="支出" value="expense" />
          </el-select>
        </el-form-item>
        <el-form-item label="交易方式">
          <el-select v-model="searchForm.paymentMethod" placeholder="请选择" clearable>
            <el-option label="微信支付" value="wechat" />
            <el-option label="支付宝" value="alipay" />
            <el-option label="银行卡" value="bank" />
            <el-option label="现金" value="cash" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column prop="date" label="交易时间" width="180" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.type === 'income' ? 'success' : 'danger'">
              {{ row.type === 'income' ? '收入' : '支出' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="{ row }">
            <span :class="{ 'income': row.type === 'income', 'expense': row.type === 'expense' }">
              {{ row.type === 'income' ? '+' : '-' }}¥{{ row.amount.toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="paymentMethod" label="交易方式" width="120">
          <template #default="{ row }">
            {{ getPaymentMethodLabel(row.paymentMethod) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="说明" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewDetail(row)">
              详情
            </el-button>
            <el-button 
              v-if="row.status === 'pending'"
              type="danger" 
              link 
              @click="handleCancel(row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增记录对话框 -->
    <el-dialog
      v-model="recordDialogVisible"
      :title="recordForm.id ? '编辑记录' : '新增记录'"
      width="500px"
    >
      <el-form
        ref="recordFormRef"
        :model="recordForm"
        :rules="recordRules"
        label-width="100px"
      >
        <el-form-item label="收支类型" prop="type">
          <el-radio-group v-model="recordForm.type">
            <el-radio label="income">收入</el-radio>
            <el-radio label="expense">支出</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number
            v-model="recordForm.amount"
            :min="0"
            :precision="2"
            :step="0.01"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="recordForm.category" placeholder="请选择">
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="交易方式" prop="paymentMethod">
          <el-select v-model="recordForm.paymentMethod" placeholder="请选择">
            <el-option label="微信支付" value="wechat" />
            <el-option label="支付宝" value="alipay" />
            <el-option label="银行卡" value="bank" />
            <el-option label="现金" value="cash" />
          </el-select>
        </el-form-item>
        <el-form-item label="交易时间" prop="date">
          <el-date-picker
            v-model="recordForm.date"
            type="datetime"
            placeholder="选择日期时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input
            v-model="recordForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="recordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRecordSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 提现对话框 -->
    <el-dialog
      v-model="withdrawDialogVisible"
      title="申请提现"
      width="500px"
    >
      <el-form
        ref="withdrawFormRef"
        :model="withdrawForm"
        :rules="withdrawRules"
        label-width="100px"
      >
        <el-form-item label="提现金额" prop="amount">
          <el-input-number
            v-model="withdrawForm.amount"
            :min="0"
            :max="accountBalance"
            :precision="2"
            :step="100"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="提现方式" prop="method">
          <el-select v-model="withdrawForm.method" placeholder="请选择">
            <el-option label="微信" value="wechat" />
            <el-option label="支付宝" value="alipay" />
            <el-option label="银行卡" value="bank" />
          </el-select>
        </el-form-item>
        <el-form-item 
          v-if="withdrawForm.method === 'bank'"
          label="银行卡号"
          prop="bankAccount"
        >
          <el-input v-model="withdrawForm.bankAccount" placeholder="请输入银行卡号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="withdrawForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="withdrawDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleWithdrawSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import {
  getMerchantBalance,
  getMerchantSettlementList,
  applyMerchantSettlement,
  getMerchantIncomeStatistics,
  getMerchantExpenseStatistics,
  getMerchantFinanceList,
  createMerchantFinanceRecord,
  updateMerchantFinanceRecord,
  cancelMerchantFinanceRecord,
  exportMerchantFinanceList
} from '@/api/merchant'

// 统计数据
const accountBalance = ref(0)
const pendingSettlement = ref(0)
const nextSettlementTime = ref('')

const monthlyIncome = reactive({
  value: 0,
  lastMonth: 0,
  trend: 0
})

const monthlyExpense = reactive({
  value: 0,
  lastMonth: 0,
  trend: 0
})

// 图表相关
const trendTimeRange = ref('month')
const trendChartRef = ref(null)
const compositionChartRef = ref(null)
let trendChart = null
let compositionChart = null

// 表格相关
const loading = ref(false)
const searchForm = reactive({
  dateRange: [],
  type: '',
  paymentMethod: ''
})
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})
const tableData = ref([])

// 分类选项
const categoryOptions = [
  { label: '订单收入', value: 'order_income' },
  { label: '退款支出', value: 'refund_expense' },
  { label: '提现支出', value: 'withdraw_expense' },
  { label: '其他收入', value: 'other_income' },
  { label: '其他支出', value: 'other_expense' }
]

// 记录表单
const recordDialogVisible = ref(false)
const recordFormRef = ref(null)
const recordForm = reactive({
  id: '',
  type: 'income',
  amount: 0,
  category: '',
  paymentMethod: '',
  date: '',
  description: ''
})

// 提现表单
const withdrawDialogVisible = ref(false)
const withdrawFormRef = ref(null)
const withdrawForm = reactive({
  amount: 0,
  method: '',
  bankAccount: '',
  remark: ''
})

// 表单验证规则
const recordRules = {
  type: [{ required: true, message: '请选择收支类型', trigger: 'change' }],
  amount: [
    { required: true, message: '请输入金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'blur' }
  ],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  paymentMethod: [{ required: true, message: '请选择交易方式', trigger: 'change' }],
  date: [{ required: true, message: '请选择交易时间', trigger: 'change' }],
  description: [{ required: true, message: '请输入说明', trigger: 'blur' }]
}

const withdrawRules = {
  amount: [
    { required: true, message: '请输入提现金额', trigger: 'blur' },
    { type: 'number', min: 100, message: '提现金额不能小于100元', trigger: 'blur' }
  ],
  method: [{ required: true, message: '请选择提现方式', trigger: 'change' }],
  bankAccount: [
    { 
      required: true, 
      message: '请输入银行卡号', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (withdrawForm.method === 'bank' && !value) {
          callback(new Error('请输入银行卡号'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 初始化图表
const initCharts = () => {
  trendChart = echarts.init(trendChartRef.value)
  compositionChart = echarts.init(compositionChartRef.value)
  window.addEventListener('resize', handleResize)
}

// 处理窗口大小变化
const handleResize = () => {
  trendChart?.resize()
  compositionChart?.resize()
}

// 更新趋势图
const updateTrendChart = (data) => {
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['收入', '支出', '结余']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.dates
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [
      {
        name: '收入',
        type: 'bar',
        stack: 'total',
        data: data.income
      },
      {
        name: '支出',
        type: 'bar',
        stack: 'total',
        data: data.expense.map(v => -v)
      },
      {
        name: '结余',
        type: 'line',
        data: data.balance
      }
    ]
  }
  trendChart?.setOption(option)
}

// 更新构成图
const updateCompositionChart = (data) => {
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ]
  }
  compositionChart?.setOption(option)
}

// 获取统计数据
const getStatisticsData = async () => {
  try {
    // 获取账户余额
    const { data: balanceData } = await getMerchantBalance()
    accountBalance.value = balanceData.balance
    pendingSettlement.value = balanceData.pendingSettlement
    nextSettlementTime.value = balanceData.nextSettlementTime

    // 获取月度收入统计
    const { data: incomeData } = await getMerchantIncomeStatistics()
    Object.assign(monthlyIncome, incomeData)

    // 获取月度支出统计
    const { data: expenseData } = await getMerchantExpenseStatistics()
    Object.assign(monthlyExpense, expenseData)

    // 获取收支趋势数据
    const params = {
      timeRange: trendTimeRange.value,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    }
    const { data: trendData } = await getMerchantFinanceList(params)
    updateTrendChart(trendData.trend)
    updateCompositionChart(trendData.composition)
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取收支明细列表
const getFinanceList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1],
      page: page.current,
      size: page.size
    }
    const { data } = await getMerchantFinanceList(params)
    tableData.value = data.list
    page.total = data.total
  } catch (error) {
    console.error('获取收支明细失败:', error)
    ElMessage.error('获取收支明细失败')
  } finally {
    loading.value = false
  }
}

// 获取支付方式标签
const getPaymentMethodLabel = (method) => {
  const methodMap = {
    wechat: '微信支付',
    alipay: '支付宝',
    bank: '银行卡',
    cash: '现金'
  }
  return methodMap[method] || method
}

// 获取状态标签
const getStatusTag = (status) => {
  const statusMap = {
    pending: 'warning',
    success: 'success',
    failed: 'danger',
    cancelled: 'info'
  }
  return statusMap[status] || ''
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const statusMap = {
    pending: '处理中',
    success: '成功',
    failed: '失败',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

// 搜索
const handleSearch = () => {
  page.current = 1
  getFinanceList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 新增记录
const handleAddRecord = () => {
  Object.keys(recordForm).forEach(key => {
    recordForm[key] = key === 'type' ? 'income' : ''
  })
  recordForm.date = new Date().toISOString().slice(0, 19).replace('T', ' ')
  recordDialogVisible.value = true
}

// 提交记录
const handleRecordSubmit = async () => {
  if (!recordFormRef.value) return
  
  try {
    await recordFormRef.value.validate()
    if (recordForm.id) {
      await updateMerchantFinanceRecord(recordForm.id, recordForm)
      ElMessage.success('更新成功')
    } else {
      await createMerchantFinanceRecord(recordForm)
      ElMessage.success('创建成功')
    }
    recordDialogVisible.value = false
    getFinanceList()
    getStatisticsData()
  } catch (error) {
    console.error('提交记录失败:', error)
  }
}

// 查看详情
const handleViewDetail = (row) => {
  Object.assign(recordForm, row)
  recordDialogVisible.value = true
}

// 取消记录
const handleCancel = async (row) => {
  try {
    await ElMessageBox.confirm('确认取消该记录吗？', '提示', {
      type: 'warning'
    })
    await cancelMerchantFinanceRecord(row.id)
    ElMessage.success('取消成功')
    getFinanceList()
    getStatisticsData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消记录失败:', error)
    }
  }
}

// 申请提现
const handleWithdraw = () => {
  withdrawForm.amount = accountBalance.value
  withdrawForm.method = ''
  withdrawForm.bankAccount = ''
  withdrawForm.remark = ''
  withdrawDialogVisible.value = true
}

// 提交提现
const handleWithdrawSubmit = async () => {
  if (!withdrawFormRef.value) return
  
  try {
    await withdrawFormRef.value.validate()
    await applyMerchantSettlement(withdrawForm)
    ElMessage.success('提现申请已提交')
    withdrawDialogVisible.value = false
    getStatisticsData()
  } catch (error) {
    console.error('提交提现失败:', error)
  }
}

// 导出数据
const handleExport = async () => {
  try {
    const params = {
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    }
    await exportMerchantFinanceList(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出数据失败:', error)
    ElMessage.error('导出数据失败')
  }
}

// 分页大小变化
const handleSizeChange = (val) => {
  page.size = val
  getFinanceList()
}

// 页码变化
const handleCurrentChange = (val) => {
  page.current = val
  getFinanceList()
}

// 监听时间范围变化
watch(trendTimeRange, () => {
  getStatisticsData()
})

onMounted(() => {
  initCharts()
  getStatisticsData()
  getFinanceList()
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  trendChart?.dispose()
  compositionChart?.dispose()
})
</script>

<style lang="scss" scoped>
.finance-management {
  padding: 20px;

  .statistics-cards {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .card-value {
      font-size: 24px;
      font-weight: bold;
      color: #303133;
      margin: 10px 0;
    }

    .card-footer {
      font-size: 13px;
      color: #909399;
    }
  }

  .chart-row {
    margin-bottom: 20px;

    .chart-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .chart-container {
        height: 300px;
      }
    }
  }

  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-actions {
        display: flex;
        gap: 10px;
      }
    }

    .search-form {
      margin-bottom: 20px;
    }

    .income {
      color: #67c23a;
    }

    .expense {
      color: #f56c6c;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 